﻿using System;
using System.Text;
using UnityEngine;
using System.Collections.Generic;

public class Packer
{
	public Action OnRequest;
	public Action<RecData> OnCallback;

	private int headLength;
	public BaseSocket Socket;

	public Packer(BaseSocket s)
	{
		Socket = s;
		headLength = ConstantDef.headLength;
	}

	/// <summary>	/// <summary>
	/// The list to add Tcp data 
	/// </summary>
	private List<SendData> reqList = new List<SendData>();

	/// Send request
	/// </summary>
	public void Add(SendData tcp) {
		reqList.Add(tcp);
	}

	public void AddRange(IEnumerable<SendData> list) {
		reqList.AddRange(list);
	}

	public void Send() {
		if (reqList.Count <= 0) {
			return;
		}

		//正在发送
		SendData tcpData;
		int count = reqList.Count;
		for (int i = 0; i < count; i++) {
			tcpData = reqList[i];
			if (tcpData.IsSending) {
				continue;
			}

			Socket.Send(tcpData);

			if (tcpData.NeedWait) {
				if (OnRequest != null) {
					OnRequest();
				}

				//等待此次请求结束，清空请求列表
				break;
			}
		}
		reqList.Clear();
	}

	public void Pack(byte[] bytes) {
		byte[] methodBuffer = new byte[headLength];
		Buffer.BlockCopy(bytes, 0, methodBuffer, 0, headLength);

		//		MemoryStream stream = new MemoryStream(bytes);
		//		byte[] method = new byte[headLength];
		//		stream.Read(method, 0, headLength);
		short method = BitConverter.ToInt16(methodBuffer, 0);
		bool isCallback = (method & 1 << headLength * 8 - 1) > 0;
		method = (short)(method & ~(1 << headLength * 8 - 1));
		string content = Encoding.UTF8.GetString(bytes, headLength, bytes.Length - headLength);

		RecData data = new RecData(method, content, TcpState.Success);

		if (isCallback) {
			if (OnCallback != null) {
				OnCallback(data);
			}
		}

		Debug.Log("method " + method + " content is : " + content);
	}
}
